<template>
  <el-dialog
    :title="view === 'create'? '新增广告': '编辑广告'"
    :visible="true"
    custom-class="dialogWrapper"
    :before-close="closeDialog">
    <el-form :model="formData" label-width="80px" ref="ruleForm" :rules="rules">
      <el-form-item v-if="bannerType == '01'|| bannerType == '03'" label="图片名称" prop="name">
        <el-input v-model.trim="formData.name" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item v-if="bannerType == '00'" label="关联商品" prop="productName">
        <!-- <el-input v-model.trim="formData.productNo" auto-complete="off"></el-input> -->
          <el-autocomplete 
            v-model.trim="formData.productName" 
            :fetch-suggestions="querySearchAsync" 
            @select="handleSelect"
            placeholder="请输入关联商品名称"
          >
          </el-autocomplete>
      </el-form-item>
      
      <el-form-item label="排序" prop="seq">
        <el-input v-model.trim="formData.seq" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item v-if="bannerType == '01'|| bannerType == '03'" label="跳转url" prop="url">
        <el-input v-model.trim="formData.url" auto-complete="off"></el-input>
      </el-form-item>
      <el-form-item v-if="bannerType == '01'|| bannerType == '03'" label="图片" prop="img">
      	<div class="editImg" v-if="imgShow === 'edit'">
      		<img :src="imgSrc(formData.picUrl)" />
      	</div>
        <el-upload
          ref="upload"
				  :action="baseUrl()"
				  list-type="picture-card"
				  accept="image/jpeg,image/gif,image/png,image/bmp"
				  :on-remove="handleRemove"
				  :on-change="handleChangeImg"
				  :auto-upload = "false"
          :before-remove="beforeRemove"
          :on-exceed="handleExceed"
					:limit="1"
					:file-list="fileList"
				  :drag="false"
				  >
				  <i class="el-icon-plus"></i>
				  <div slot="tip" class="el-upload__tip">建议尺寸：800*450</div>
				</el-upload>
				<el-dialog :visible.sync="dialogVisible" size="tiny">
				  <img width="100%" :src="dialogImageUrl" alt="">
				</el-dialog>
     </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取 消</el-button>
      <el-button type="info" @click="submit('ruleForm')" :disabled="Subabled">确 定</el-button>
    </div>
  </el-dialog>
</template>

<script>
import {seachPro} from "@/services/module";
import { oneFile} from "@/services/getFromData";
import { RequestError } from "@/services/errors";
import { mapActions } from "vuex";
import editorImage from "@/components/Tinymce/components/editorImage";
var serialize = require('form-serialize');
// import {login} from '@/services/login'
// import menuModules from '@/router/modules.json'
export default {
  name: "edit-advert",
  data () {
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请选择权限'));
      } else {
        callback();
      }
    }
    return {
      menus: [],
      list: [],
      file:{},
			fileList:[],
      institutionNo:"",
      moduleNo:"",
      bannerType:"",
      id:"",
      formData: {
        name: "",
        seq: "",
        url: "",
        productNo:"",
        productName:""
      },
      productNo:"",
      Subabled:false,
      imgShow:"",
      dialogImageUrl: '',
      dialogVisible: false,
      dialogFormVisible: false,
      menuInfo: [],
      rules: {
        productName: [{ required: true, message: "请输入关联商品名称", trigger: "change" },
        { min: 1, max: 50, message: '长度在 20个字符以内', trigger: 'blur' }],
        name: [{ required: true, message: "请输入图片名称", trigger: "blur" },
        { min: 1, max: 20, message: '长度在 20个字符以内', trigger: 'blur' }],
        seq: [{ required: true, message: "请输入排序", trigger: "blur" },
        { min: 1, max: 11, message: '长度在 11个字符以内', trigger: 'blur' }],
      }
    }
  },
  props: {
    view: {
      type: String,
      default: "create"
    }
  },
  created(){
  },
  methods: {
    ...mapActions(["setUserInfo"]),
    closeDialog() {
      this.$emit("close");
    },
    baseUrl(){
    	return "api/console/institution/addBanner.do";
    },
    imgSrc(data){
      	return this.$store.state.imgUrl + data;
    },
		handleRemove(file, fileList) {
    	this.file = "";
 	  },
    beforeRemove(file, fileList) {
			return this.$confirm(`确定移除 ${ file.name }？`);
		},
		handleExceed(files, fileList) {
			this.$message.warning(`当前限制只能导入 1 个文件`);
		},
    handleChangeImg(file, fileList){
				this.file = file.raw;
				this.imgShow = ""
				this.regImage(file);
        this.regMemory(file);
		},
		regMemory(file){
			const isLt10M = file.size / 1024 / 1024 < 2;
			if (!isLt10M) {
				this.$refs.upload.clearFiles();
				this.$message.error('上传图片大小不能超过 2MB!');
				this.file = ""
			}
		},
		regImage(file){
			var path = file.raw.name;  //得到的是现在文件的路径
			var Suffix = path.substr(path.lastIndexOf(".")).toUpperCase();//得到的是后缀名,且转换为大写
			// console.log(Suffix)
			if(Suffix != ".JPG" && Suffix !=".PNG" && Suffix !=".JPEG"){
				  this.$refs.upload.clearFiles();
					this.$message.error('上传图片只能是 JPG/PNG 格式！');
					this.file = ""
			}
		},
    async querySearchAsync(queryString, callback) {
      try {
        	// let insId = id.toString()
          let data = await seachPro(queryString)
          for(let item of data.data){
              item.value = item.productName;  //将想要展示的数据作为value
          }
          callback(data.data)
        } catch (e) {
          if (e instanceof RequestError) {
            this.$alert(e.message, '提示', {
              type: 'error',
              confirmButtonText: '确定'
            })
          } else {
            throw e
          }
        }
    },
    handleSelect(item) {
      this.formData.productNo = item.productNo;
      this.formData.productName = item.productName;
    },
    submit(formName) {
      this.Subabled = true;
      this.butTimeOut();
      this.$refs[formName].validate(async valid => {
        if (valid) {
          try {
            if (this.view === "create") {
							var sref = this;
            	//把图片的信息和参数放进请求头里
            	let code = await oneFile({
                institutionNo:this.institutionNo,
                moduleNo:this.moduleNo,
                bannerType:this.bannerType,
				        name: this.formData.name,
				        seq: this.formData.seq,
                url: this.formData.url,
                productNo:this.formData.productNo,
                productName:this.formData.productName
				      },"/ecshop/module/addModuleBanner.do","logoPicUrl",sref.file).then(
								function(data){
									sref.$message({
										showClose: true,
										message: data,
										type: "success"
									});
									sref.$emit("close", true);
								}, 
								function(reason, data){
									sref.$message({
										showClose: true,
										message: reason,
										type: "error"
									});
								});
	          } 
            else {
							var sref = this;
              let code = await oneFile({
                moduleNo:this.moduleNo,
                bannerType:this.bannerType,
                id: this.formData.id,
				    		institutionNo:this.formData.institutionNo,
				        name: this.formData.name,
				        seq: this.formData.seq,
                url: this.formData.url,
                productNo:this.formData.productNo,
                productName:this.formData.productName
				      },"/ecshop/module/updateModuleBanner.do","logoPicUrl",sref.file).then(
								function(data){
									sref.$message({
										showClose: true,
										message: data,
										type: "success"
									});
									sref.$emit("close", true);
								}, 
								function(reason, data){
									sref.$message({
										showClose: true,
										message: reason,
										type: "error"
									});
								});
            }
            this.dialogFormVisible = false;
          } catch (e) {
            if (e instanceof RequestError) {
              this.$alert(e.message, "提示", {
                type: "error",
                confirmButtonText: "确定"
              });
            } else {
              throw e;
            }
          }
        } else {
          return;
        }
      });
    },
    butTimeOut(){
      var serf = this;
      setTimeout(function(){
        serf.Subabled = false;
      },1200)
    }
  },
  mounted() {},
  components: {
      'editorImage': editorImage
    }
};
</script>
<style>
.dialogWrapper {
  width: 540px;
}
.el-select {
  width: 100%;
}
.editImg{
	  overflow: hidden;
    background-color: #fff;
    border: 1px solid #c0ccda;
    border-radius: 6px;
    box-sizing: border-box;
    width: 148px;
    height: 148px;
    margin: 0 8px 8px 0;
    display: inline-block;
    float: left;
}
.editImg img{
	width: 100%;
	height: 100%;
}
</style>
